package com.kyxx.topics.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.MemberDetailAdapter;
import com.kyxx.topics.adapter.MemberShopAdapter;
import com.kyxx.topics.bean.MemberDetailBean;
import com.kyxx.topics.bean.MemberPromotion;
import com.kyxx.topics.bean.MembershipCardBean;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class MemberDeatailActivity extends BaseActivity implements MemberShopAdapter.OnItemClickLitener {
    @Bind(R.id.iv_back)
    ImageView iv_back;
    @Bind(R.id.rv_member_detail)
    RecyclerView rv_member_detail;
    @Bind(R.id.swipe_member_detail)
    SwipeRefreshLayout swipe_member_detail;
    @Bind(R.id.tv_member_shop)
    TextView tv_member_shop;
    @Bind(R.id.ck_member_check)
    CheckBox ck_member_check;
    @Bind(R.id.rl_member_shop)
    RelativeLayout rl_member_shop;
    @Bind(R.id.view)
    View view;

    private MemberDetailAdapter adapter;
    private MemberShopAdapter shopAdapter;
    private MemberDetailBean bean;
    private List<MemberDetailBean.Shop> shopList;
    private List<MemberPromotion> promotions;
    private String type_id;
    private MembershipCardBean shipBean;
    private static final int Notify = 1;
    private static final int LOADPROMOTION = 2;
    boolean ischeck = false;
    private PopupWindow popupWindow;
    private RecyclerView rc_memeber_shop;
    private int shopPosition;

    protected void findViewById() {
    }

    protected void loadViewLayout() {
        setContentView(R.layout.activity_member_detail);
        ButterKnife.bind(this);
        shipBean = (MembershipCardBean) getIntent().getSerializableExtra("bean");
        if (shipBean != null) {
            type_id = shipBean.getType_id();
        } else {
            type_id = getIntent().getStringExtra("type_id");
        }
        promotions = new ArrayList<>();
        bean = new MemberDetailBean();
        shopList = new ArrayList<>();
    }


    protected void processLogic() {
        rv_member_detail.setLayoutManager(new LinearLayoutManager(this));
        rv_member_detail.setHasFixedSize(true);//适配器内容改变，不会改变RecyclerView的大小
        swipe_member_detail.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        initPopuWindow();
        refresh();
        ck_member_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    if (!popupWindow.isShowing()) {
                        popupWindow.showAsDropDown(view);
                    }
                } else {
                    if (!popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    ischeck = false;
                }
            }
        });
    }

    protected void setListener() {
    }

    private void refresh() {
        loadData();
    }

    @OnClick({R.id.iv_back, R.id.rl_member_shop,R.id.tv_member_edit})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_member_shop:
                ck_member_check.setChecked(!ischeck);
                if (ischeck) {
                    ischeck = false;
                } else {
                    ischeck = true;
                }
                break;
            case R.id.tv_member_edit:
                startActivity(new Intent(MemberDeatailActivity.this,EditMemberActivity.class).putExtra("shipBean",shipBean));
                finish();
        }
    }

    private void loadData() {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("type_id", type_id);
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD_INFO, context, "vip_item" + type_id, CacheMode.REQUEST_FAILED_READ_CACHE, params, new LoadingStringCallBack(MemberDeatailActivity.this,false) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    bean = JSONObject.parseObject(result.getJSONObject("data").toString(), MemberDetailBean.class);
                    shopList = bean.getList();
                    if (bean.getList().size() > 0) {
                        mHandler.sendEmptyMessage(LOADPROMOTION);
                    } else {
                        mHandler.sendEmptyMessage(Notify);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }

    private void loadPromotion(String sid) {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        obj.put("sid", sid);
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD_PROMOTION, context, "vip_promotion" + sid, CacheMode.REQUEST_FAILED_READ_CACHE, params, new LoadingStringCallBack(MemberDeatailActivity.this,false) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    if (result.getInt("code") == 0) {
                        promotions = JSONObject.parseArray(result.getJSONArray("data").toString(), MemberPromotion.class);
                        mHandler.sendEmptyMessage(Notify);
                    } else {
                        ToastUtils.show(context, result.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }

    Handler mHandler = new Handler() {
        @Override
        public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
            switch (msg.what) {
                case Notify:
                    if (swipe_member_detail.isRefreshing()) {
                        swipe_member_detail.setRefreshing(false);
                    }
                    adapter = new MemberDetailAdapter(MemberDeatailActivity.this, bean, promotions, shipBean,shopPosition);
                    rv_member_detail.setAdapter(adapter);
                    shopAdapter = new MemberShopAdapter(context, shopList);
                    rc_memeber_shop.setAdapter(shopAdapter);
                    shopAdapter.setOnItemClickLitener(MemberDeatailActivity.this);
                    if(shopList.size()>0){
                        tv_member_shop.setText(shopList.get(shopPosition).getShop_name());
                        ck_member_check.setVisibility(View.VISIBLE);
                    }else{
                        tv_member_shop.setText("会员卡详情");
                        ck_member_check.setVisibility(View.GONE);
                    }

                    break;
                case LOADPROMOTION:
                    loadPromotion(bean.getList().get(0).getSid());
                    break;
            }

            return super.sendMessageAtTime(msg, uptimeMillis);
        }
    };

    private void initPopuWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.pop_member_detail, null);
        if (rc_memeber_shop == null) {
            rc_memeber_shop = (RecyclerView) view.findViewById(R.id.rc_pop_shop);
            rc_memeber_shop.setLayoutManager(new LinearLayoutManager(this));
        }
        //自适配长、框设置
        popupWindow = new PopupWindow(view, RecyclerView.LayoutParams.MATCH_PARENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ischeck = false;
                ck_member_check.setChecked(ischeck);
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        shopPosition=position;
        tv_member_shop.setText(shopList.get(position).getShop_name());
        loadPromotion(bean.getList().get(position).getSid());
        popupWindow.dismiss();
        ischeck = false;
        ck_member_check.setChecked(ischeck);
    }


}